package com.example.demo;

import com.example.demo.convertors.BooleanTypeConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraCqlClusterFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.mapping.CassandraMappingContext;
import org.springframework.data.convert.CustomConversions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Configuration
//@EnableCassandraRepositories("com.example.demo.repositories")
public class CassandraConfig extends AbstractCassandraConfiguration {

  private static final String KEYSPACE_NAME = "cassandra";
  private static final String HOSTNAME = "0.0.0.0";
  private static final int PORT = 9042;

  @Override
  protected String getKeyspaceName() {
    return KEYSPACE_NAME;
  }

  @Bean
  public CassandraClusterFactoryBean cluster() {
    CassandraCqlClusterFactoryBean bean = new CassandraCqlClusterFactoryBean();
    bean.setContactPoints(HOSTNAME);
    bean.setPort(PORT);
    bean.setKeyspaceCreations(getKeyspaceCreations());
    return bean;
  }

  @Override
  protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
    List<CreateKeyspaceSpecification> createKeyspaceSpecifications =
            new LinkedList();
    createKeyspaceSpecifications.add(getKeyspaceSpecification());
    return createKeyspaceSpecifications;
  }

  // Create keyspace if it doesn't already exist
  private CreateKeyspaceSpecification getKeyspaceSpecification() {
    return CreateKeyspaceSpecification.createKeyspace(getKeyspaceName())
            .ifNotExists(true);
  }

  @Override
  public String[] getEntityBasePackages() {
    return new String[] {"org.hl7.fhir.dstu3.model"};
  }

  @Override
  public SchemaAction getSchemaAction() {
    return SchemaAction.RECREATE_DROP_UNUSED;
  }

  @Override
  public CustomConversions customConversions() {
    List<Converter<?,?>> converters = new ArrayList();
    converters.add(new BooleanTypeConverter.BooleanTypeReadConverter());
    converters.add(new BooleanTypeConverter.BooleanTypeWriteConverter());
    return new CustomConversions(CustomConversions.StoreConversions.NONE, converters);
  }
}

